<template>
  <ele-page flex-table>
    <!-- 搜索表单 -->
    <PageSearch :warehouseList="warehouseList" @search="reload" />

    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        v-model:selections="selections"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        cache-key="StockEnterTable"
      >
        <template #toolbar>
          <el-button type="primary" class="ele-btn-icon" :icon="Plus" @click="openPageTab('EDIT')">
            新增盘点单
          </el-button>
          <el-button type="primary" plain class="ele-btn-icon" :icon="Plus" @click="showEditOne = true">
            单商品盘点
          </el-button>
        </template>

        <template #order_sn="{ row }">
          <el-link type="primary" @click="onCommand('INFO', row)">{{ row.order_sn }}</el-link>
        </template>
        <template #review_status="{ row }">
          <el-tag :type="getType(row.review_status)">{{ row.review_status_name }}</el-tag>
        </template>
        <template #status="{ row }">
          <el-tag :type="getType(row.status)">{{ row.status_name }}</el-tag>
        </template>
        <template #action="{ row }">
          <div class="flex-ea">
            <template v-if="row.acts.length">
              <ele-dropdown
                :items="row.acts"
                @command="value => onCommand(value, row)"
              >
                <el-button
                  type="primary"
                  link
                >
                  <el-icon :size="16" class="block ml-4px"><IconElEditPen /></el-icon>
                </el-button>
              </ele-dropdown>
              <el-divider direction="vertical" />
            </template>
            <el-link type="primary" @click="onCommand('INFO', row)">
              详情
            </el-link>
          </div>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <PageEditOne v-model="showEditOne" :warehouseList="warehouseList" @done="reload" />
    <PageInfo v-model="showInfo" :data="current" />

    <PageReview v-model="showReview" :statusList="[{ value: 'YD', label: '过账' }, { value: 'PD', label: '再盘点' }]" remarkDisabled @done="review" />
  </ele-page>
</template>

<script setup>
import { ListToWarehouse } from '@/api/common'
import PageReview from '@/components/Common/Review.vue'
import { Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import PageEditOne from './components/edit-one.vue'

import PageInfo from './components/info.vue'
import PageSearch from './components/search.vue'

const showReview = ref(false)

const router = useRouter()
const { getType } = utils
const [warehouseList] = utils.useGetList(ListToWarehouse)
/** 表格实例 */
const tableRef = ref(null)

// 激活页面刷新table
utils.useActivatedReload(() => tableRef.value?.reload?.())

const { addPageTab } = utils.usePageTab()

/** 表格列配置 */
const columns = ref([
  {
    type: 'index',
    label: '序',
    width: 50,
    align: 'center',
    fixed: 'left',
  },
  {
    prop: 'order_sn',
    label: '单据编号',
    width: 180,
    align: 'left',
    slot: 'order_sn',
  },
  {
    prop: 'order_date',
    label: '单据日期',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'product_num',
    label: '品数',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'num',
    label: '盘点数量',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'diff_num',
    label: '盘点差异',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'stock',
    label: '库存数',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'mch_name',
    label: '平台',
    minWidth: 100,
    align: 'center',
  },
  // {
  //   prop: 'supplier_name',
  //   label: '货主',
  //   minWidth: 100,
  //   align: 'center',
  // },
  {
    prop: 'warehouse_name',
    label: '仓库',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'status_name',
    label: '状态',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'create_user_name',
    label: '创建人',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'create_time',
    label: '创建时间',
    formatter: (row) => {
      return utils.formatDate(row.create_time)
    },
    align: 'center',
    width: 160,
    showOverflowTooltip: false,
  },
  {
    columnKey: 'action',
    label: '操作',
    align: 'right',
    slot: 'action',
    fixed: 'right',
    showOverflowTooltip: false,
    width: 100,
  },
])

/** 表格选中数据 */
const selections = ref([])

/** 当前编辑数据 */
const current = ref(null)

/** 是否显示编辑弹窗 */
const showEditOne = ref(false)

const showInfo = ref(false)

/** 表格数据源 */
async function datasource({ page, limit, where, orders }) {
  const res = await utils.get('/stockInventory/index', { ...where, ...orders, page, limit })
  res.data.forEach((v) => {
    v.acts = getActs(v, true)
  })
  return res
}

/** 搜索 */
function reload(where) {
  selections.value = []
  tableRef.value?.reload?.({ page: 1, where })
}

/** 打开编辑弹窗 */
function openPageTab(row, tag = 'edit') {
  const id = row?.id ?? 0
  const path = `/stock/inventory/${tag}/${id}`

  addPageTab({
    key: path,
    closable: true,
  })
  router.push(path)
}

function review(data, cb) {
  const id = current.value?.id ? [current.value.id] : selections.value.map(v => v.id)
  updateStatus({
    id,
    status: data.status,
  }, cb)
}

function updateStatus(formData, cb) {
  const loading = utils.message('请求中..', 'loading')
  utils.post('/stockInventory/review', formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      showReview.value = false
      reload()
    }
  }).finally(() => {
    cb && cb()
    loading.close()
  })
}

function onCommand(command, row) {
  current.value = row?.id ? row : null
  const id = row?.id ? row.id : selections.value[0].id

  if (['INFO', 'EDIT'].includes(command)) {
    const _row = row?.id ? row : selections.value[0]
    openPageTab(_row, command.toLowerCase())
  }
  else if (command === 'CD') {
    utils.confirm('确定要<span class="px-2px text-danger font-semibold">取消</span>盘点单吗', '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
      cancelButtonText: '不取消了',
      confirmButtonText: '确定取消',
    }).then(() => {
      updateStatus({ id, status: 'CD' })
    })
  }
  else if (command === 'YD') {
    showReview.value = true
  }
  else {
    // YS 审核通过 NS 审核不通过 FS 反审 OK 已结单
    const list = [
      { key: 'PD', title: '开始盘点' },
      { key: 'TJ', title: '提交' },
      { key: 'QR', title: '确认' },
    ]
    const item = list.find(v => v.key === command)
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">${item.title}</span>订单吗`, '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      const ids = row?.id ? [row.id] : selections.value.map(v => v.id)
      const formData = {
        id: ids,
        status: command,
      }
      updateStatus(formData)
    })
  }
}

function getActs(row, filter = false) {
  const list = [
    { title: '编辑', command: 'EDIT', disabled: row.is_ed !== 1, icon: 'IconElEdit' },
    { title: '开始', command: 'PD', disabled: row.is_pd !== 1, icon: 'IconElOpen' },
    { title: '提交', command: 'TJ', disabled: row.is_tj !== 1, icon: 'IconElPromotion' },
    { title: '确认', command: 'QR', disabled: row.is_qr !== 1, icon: 'IconElStamp' },
    { title: '审核', command: 'YD', disabled: row.is_yd !== 1, icon: 'IconElCheck' },
    { title: '取消', command: 'CD', disabled: row.is_cd !== 1, icon: 'IconElClose' },
  ]
  if (filter) {
    return list.filter(v => !v.disabled)
  }
  return list
}
</script>
